package com.banksoft.cps.controller;


import com.banksoft.cps.bean.lora.LoraData;
import com.banksoft.cps.service.LoraDataService;
import com.banksoft.cps.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by rongzhao.zhu on 2018/7/19.
 */
@Controller
@RequestMapping("/front/lora/")
public class FrontLoraController extends ControllerConstants {

     @Autowired
    LoraDataService loraDataService;

    @RequestMapping(value = "pushData", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String pushData(HttpServletRequest request){
        System.out.println("接收到上传数据++++++++++++++++++++++++++++++++++");
        String jsonData =  getJsonParam(request);
        LoraData loraData = JsonUtils.decode(jsonData,LoraData.class);
        loraDataService.handle(loraData);

        System.out.println("++++++++++++++++++++++++++++++++++");
        return toJSONString(SUCCESS);
    }



    @RequestMapping(value = "upData", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String list(HttpServletRequest request){
        System.out.println("接收到上传数据++++++++++++++++++++++++++++++++++");
        String jsonData =  getJsonParam(request);

        System.out.println("++++++++++++++++++++++++++++++++++");
        return toJSONString(SUCCESS);
    }
    private String getJsonParam(HttpServletRequest request){
        try{
            BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);

            return  responseStrBuilder.toString();

        }catch (Exception e){
            e.printStackTrace();
        }
       return null;

    }
}
